import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.util.JdbcConstants;

import java.util.List;

public class DruidParserExample {
    public static void main(String[] args) {
        String sql = "SELECT\n" +
                "        M.\"id\" AS g_id,\n" +
                "        M.group_code AS g_code,\n" +
                "        M.group_name AS g_name,\n" +
                "        bs.guid AS servicetype,\n" +
                "        bs.servicename,\n" +
                "        pro.pcode,\n" +
                "        pro.pname,\n" +
                "        pro.prj_code,\n" +
                "        sdl.id AS sys_data_label_id,\n" +
                "        sdl.\"name\",\n" +
                "        COUNT(S.guid) AS cnt\n" +
                "        FROM\n" +
                "        cfg_server_group AS M\n" +
                "        LEFT JOIN cfg_server_group_rel AS R ON M.id = R.group_id\n" +
                "        LEFT JOIN sys_prjservice AS S ON R.server_id = S.guid\n" +
                "        LEFT JOIN sys_project AS pro ON pro.pcode = S.pcode\n" +
                "        LEFT JOIN base_services AS bs ON bs.guid = S.servicetype\n" +
                "        LEFT JOIN sys_data_label AS sdl ON sdl.ID = S.sys_data_label_id\n" +
                "        AND sdl.del_flag = '0'\n" +
                "        WHERE\n" +
                "        M.del_flag = '0' AND bs.guid IN('singleTableServer','executeSqlServer')\n" +
                "        GROUP BY\n" +
                "        M.\"id\",\n" +
                "        S.servicetype,\n" +
                "        S.pcode,\n" +
                "        pro.pcode,\n" +
                "        pro.prj_code,\n" +
                "        bs.guid,\n" +
                "        sdl.id,\n" +
                "        pro.sort,\n" +
                "        pro.pname,\n" +
                "        bs.sort,\n" +
                "        bs.servicename,\n" +
                "        sdl.sort,\n" +
                "        sdl.\"name\"\n" +
                "        ORDER BY\n" +
                "        pro.sort,\n" +
                "        bs.sort,\n" +
                "        sdl.sort";
        System.out.println(getTablesStr(sql));
    }

    public static String getTablesStr(String sql) {
        StringBuilder retn = new StringBuilder();
        // 解析SQL
        List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
        // 遍历语句并提取表名
        MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
        for (SQLStatement stmt : stmtList) {
            stmt.accept(visitor);
            retn.append(visitor.getTables().keySet().toString().replace("[", "").replace("]", ""));
        }
        return retn.toString();
    }
}